<?php

namespace common\models;


use common\models\db\AdminRole;
use common\models\db\AdminUser;
use yii\data\ActiveDataProvider;

/**
 *
 */
class AdminUserForm extends AdminUser
{

    public $password;
    public $role_name;

    public function rules()
    {
        $rules = parent::rules();
        $rules[] = [['password'], 'safe'];
        return $rules;
    }

    public function beforeSave($insert)
    {
        if ($insert && !$this->password) {
            $this->addError('password', '密码不能为空');
            return false;
        }
        if ($this->password) {
            $this->setPassword($this->password);
        }
        return parent::beforeSave($insert);
    }

    public function search($params)
    {
        $this->load($params);

        $query = AdminUserForm::find();
        $query->select('u.*, r.role_name');
        $query->alias('u');
        $query->leftJoin(AdminRole::tableName() . ' as r', 'u.role_id = r.role_id');
        $query->orderBy('u.role_id');
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        return $dataProvider;
    }

    public function toArray(array $fields = [], array $expand = [], $recursive = true)
    {
        $arr = parent::toArray($fields, $expand, $recursive);

        if ($arr['role_id'] === 0) {
            $arr['role_name'] = '系统管理员';
            $arr['deleteDisable'] = true;
            $arr['updateDisable'] = true;
        } else {
            $arr['role_name'] = $this->role_name;
        }
        return $arr;
    }
}